//
//  IGNewsArticleViewController.m
//  iGameApp
//
//  Created by lanou on 16/1/16.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "IGNewsArticleViewController.h"
#import "IGNewsArticleModel.h"
#import "IG_iGameRoundCommentModel.h"
#import "IG_RoundCommentTableViewCell.h"
#import "IGNewsArticleTableViewCell.h"
#import "IGCustomNavigationController.h"
#import "IGNewsCommentView.h"
#import "IGLoginViewController.h"

@interface IGNewsArticleViewController () <UITableViewDataSource, UITableViewDelegate, IMYWebViewDelegate,UMSocialUIDelegate, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) IMYWebView *webView;

@property (nonatomic, strong) NSMutableArray *dataArr; // 相关文章
@property (nonatomic, strong) NSMutableArray * commentArr; // 评论

@property (nonatomic, strong) IGCustomNavigationController *naviC;

// 导航栏分享按钮
@property (nonatomic, strong) UIButton *shareButton;

// 评论数
@property (nonatomic, assign) NSInteger commentNumber;

@property (weak, nonatomic) IBOutlet UILabel *bgLabel;

@property (weak, nonatomic) IBOutlet UITextField *commentTF;
@property (weak, nonatomic) IBOutlet UIButton *commentButton;
@property (nonatomic, strong) IGNewsCommentView *commentView;

@property (weak, nonatomic) IBOutlet UILabel *sofaLabel;

@property (weak, nonatomic) IBOutlet UIImageView *sofaImageView;

// 菊花
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicatorView;

@end



@implementation IGNewsArticleViewController

- (void)viewWillAppear:(BOOL)animated
{
    _naviC = (IGCustomNavigationController *)self.navigationController;
    _naviC.iconButton.hidden = YES;
    _naviC.backButton.hidden = NO;
    
    _shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _shareButton.frame = CGRectMake(kScreenWidth - 40, 9.5, 25, 25);
    [_shareButton setBackgroundImage:[UIImage imageNamed:@"shareInfo"] forState:UIControlStateNormal];
    [_shareButton addTarget:self action:@selector(shareButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_naviC.bgView addSubview:_shareButton];
    
    // 隐藏tabBar
    self.tabBarController.tabBar.hidden = YES;
    
    // 评论
    _commentView = [[UINib nibWithNibName:@"iGNewsCommentView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
    _commentView.height = 165;
    [_commentView.cancelButton addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_commentView.sendButton addTarget:self action:@selector(sendButtonClick:) forControlEvents:UIControlEventTouchUpInside];

    _commentTF.inputAccessoryView = _commentView;
    _commentTF.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated
{
    _naviC.iconButton.hidden = NO;
    _naviC.backButton.hidden = YES;
    [_shareButton removeFromSuperview];
    
    // 显示tabBar
    self.tabBarController.tabBar.hidden = NO;
    

    
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    self.view.backgroundColor = [UIColor grayColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 活动监测者
    _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    _activityIndicatorView.frame = CGRectMake((kScreenWidth - 50) / 2, 70, 50, 50);
    [self.view addSubview:_activityIndicatorView];
    [_activityIndicatorView startAnimating];

    
    // 注册cell
    [_tableView registerNib:[UINib nibWithNibName:@"IGNewsArticleTableViewCell" bundle:nil] forCellReuseIdentifier:@"articleCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"IG_RoundCommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"IG_RoundCommentTableViewCell"];
    
    _tableView.sectionHeaderHeight = 30;
    
    _dataArr = [NSMutableArray array];
    _commentArr = [NSMutableArray array];
    
    _webView = [[IMYWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 800)];
    _webView.delegate = self;
    
    NSString *requestStr = [NSString stringWithFormat:@"http://www.imbatv.cn/appnews/app_news/%@/app",_article_id];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestStr]];
    [_webView loadRequest:request];
    
    
    
}

#pragma mark -- 请求数据
- (void)requestData
{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"article_id"] = _article_id;
    
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/getRelatearticles?" parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        
        NSArray *dataArr = dataDic[@"data"];
        
        for (NSDictionary *oneDic in dataArr) {
            
            IGNewsArticleModel *model = [[IGNewsArticleModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_dataArr addObject:model];
            
        }
        
        [_tableView reloadData];
        
    } error:^(NSError *requestError) {
        NSLog(@"%@",requestError);
    }];
   
}

- (void)requestComment
{
    IG_UserMessage *user = [IG_UserMessage shareUserMessage];
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"article_id"] = _article_id;
    parDic[@"num"] = @"10";
    parDic[@"start"] = @"0";
    parDic[@"uid"] = user.dic[@"uid"];
    
    [IGAFNetworking requestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/getNewsComment?" parDic:parDic metho:GET finish:^(NSDictionary *dataDic) {
        
        NSDictionary *dic = dataDic[@"data"];
        NSString *commentStr = dic[@"counts"];
        _commentNumber = [commentStr integerValue];
        if (_commentNumber == 0) {
            
            _sofaLabel.text = @"沙发";
            _sofaImageView.image = [UIImage imageNamed:@"iconfont-iconfontshafa"];
        }else{
            
            _sofaLabel.text = [NSString stringWithFormat:@"%ld",_commentNumber];
            _sofaImageView.image = [UIImage imageNamed:@"comment"];
            
        }
        
        [_commentArr removeAllObjects];
        for (NSDictionary *oneDic in dic[@"comment"]) {
            
            IG_iGameRoundCommentModel *model = [[IG_iGameRoundCommentModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_commentArr addObject:model];
            
        }
        
        [_tableView reloadData];
        
    } error:^(NSError *requestError) {
        NSLog(@"%@",requestError);
    }];

    
}


#pragma mark -- webView
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    [_webView evaluateJavaScript:@"document.body.scrollHeight;" completionHandler:^(id height, NSError *error) {
        
        CGFloat Newheight = [height floatValue];
        CGRect newFrame = _webView.frame;
        newFrame.size.height = Newheight;
        _webView.frame = newFrame;
        
        [_activityIndicatorView stopAnimating];
        
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = _webView;
        
        
    }] ;
    
    [self requestData];
    [self requestComment];
    
}

#pragma mark -- tableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_commentArr.count > 0) {
        
        return 2;
    }else{
        return 1;
    }

    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (section > 0) {
        
        return _commentArr.count;
        
    }else{
    
        return _dataArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section > 0) {
        
        IG_iGameRoundCommentModel *model = _commentArr[indexPath.row];
        IG_RoundCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"IG_RoundCommentTableViewCell"];
        cell.model = model;
        return cell;
        
    }else{
    
        if (_dataArr.count != 0) {
            
            IGNewsArticleModel *model = _dataArr[indexPath.row];
            IGNewsArticleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"articleCell"];
            cell.model = model;
            return cell;
            
        }else{
            return nil;
        }
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section > 0) {
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 25)];
        label.text = [NSString stringWithFormat:@"评论 (%ld)",_commentNumber];
        label.backgroundColor = [UIColor grayColor];
        label.textAlignment = NSTextAlignmentCenter;
        return label;
        
    }else{
    
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 25)];
        label.text = @"相关新闻";
        label.backgroundColor = [UIColor grayColor];
        label.textAlignment = NSTextAlignmentCenter;
        return label;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        
                IGNewsArticleModel *model = _dataArr[indexPath.row];
        
        IGNewsArticleViewController *newsVC = [[IGNewsArticleViewController alloc] initWithNibName:@"IGNewsArticleViewController" bundle:nil];
        newsVC.article_id = model.article_id;
        [self.navigationController pushViewController:newsVC animated:YES];

    }
    

    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section > 0) {
        
        return 90;
        
    }else{
        return 80;
    }
    
}

// 导航栏分享按钮
- (void)shareButtonClick:(UIButton *)button
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"569748dd67e58e9965001f37"
                                      shareText:@"欢迎使用iGame"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToQQ,UMShareToEmail,UMShareToWechatFavorite,UMShareToQQ,UMShareToQzone,UMShareToSms, nil]
                                       delegate:self];

    
}


- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    IG_UserMessage *user = [IG_UserMessage shareUserMessage];
   
    BOOL islogin = user.isLoading;
    
    if (islogin == YES) {
        [self performSelector:@selector(setFristResponder) withObject:nil afterDelay:1];
    }else{
        
        [textField resignFirstResponder];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"请先登陆" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        
        [alertView show];
        
        IGLoginViewController *loginVC = [[IGLoginViewController alloc] initWithNibName:@"IGLoginViewController" bundle:nil];
        [self presentViewController:loginVC animated:YES completion:nil];
        
        
    }
}


- (void)setFristResponder
{
    [_commentView.textView becomeFirstResponder];
    [_commentTF resignFirstResponder];
}



// 取消评论
- (void)cancelButtonClick:(UIButton *)button
{
    
    [_commentView.textView resignFirstResponder];
    [_commentTF resignFirstResponder];
    _commentTF.text = _commentView.textView.text;
    
}

// 发送评论
- (void)sendButtonClick:(UIButton *)button
{
    [self sendComment];
    
    
}

// 发送评论
- (void)sendComment
{
    [_commentView.textView resignFirstResponder];
    [_commentTF resignFirstResponder];
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"article_id"] = _article_id;
    parDic[@"city"] = [@"上海市" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    parDic[@"content"] = [_commentView.textView.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    parDic[@"uid"] = @"348319";
    
    [IGAFNetworking newRequestWithUrlString:@"http://www.imbatv.cn/api_2_4_0/addNewsComment" parDic:parDic method:POST finish:^(NSDictionary *dataDic) {
        [self requestComment];
        _commentView.textView.text = nil;
    } error:^(NSError *requestError) {
        NSLog(@"%@",requestError);
    }];

}

// 滚动到评论
- (IBAction)scrollToComment:(UIButton *)sender {
   
    if (_commentNumber != 0) {
        
        if (_tableView.contentOffset.y == 0) {
            
            [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }else{
            
            [_tableView setContentOffset:CGPointMake(0, 0) animated:YES];
            
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
